﻿using System;
using System.Collections.Generic;
using System.Linq;

using TempEmployees.DAL;
using TempEmployees.BLL.Database;

namespace TempEmployees.BLL.EntitiesExtensions
{
    public static class EBudget
    {
        public static AssignedBudget AssignBudget(string userId, string budgetID, int budgetTypeId)
        {
            Budget budget = DbQuery.GetSingleRow<Budget>("ID", budgetID);
            if (budget == null)
            {
                budget = new Budget();
                budget.ID = budgetID;
                budget.TypeID = budgetTypeId;
                DbQuery.Insert<Budget>(budget);
            }

            var query = from ab in DbQuery.Database.AssignedBudgets
                        where ab.UserID == userId && ab.BudgetID == budgetID
                        select ab;
            if (query.Count() == 0) return AssignBudget(userId, budgetID);
            else return query.First<AssignedBudget>(); 
        }

        private static AssignedBudget AssignBudget(string userId, string budgetId)
        {
            AssignedBudget assigned = new AssignedBudget();
            assigned.BudgetID = budgetId;
            assigned.UserID = userId;
            DbQuery.Insert<AssignedBudget>(assigned);
            return assigned;
        }
    }
}